package org.sy.lab.多线程基础._2_同步._2_ReentrantLock._2_读写锁;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Counter {
	
	private int num = 10;
	private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
	
	public void add() {
		lock.writeLock().lock();
		System.out.println("--开始写入");
		try {
			for (int i = 0; i < 5; i++) {
				num++;
				try {
					TimeUnit.SECONDS.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			System.out.println("--结束写入");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.writeLock().unlock();
		}
	}
	
	public int read() {
		lock.readLock().lock();
		try {
			System.out.println("读取：" + num);
			return num;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.readLock().unlock();
		}
		return 0;
	}
	
	public int unsafeRead() {
		System.out.println("读取：" + num);
		return num;
	}
}
